package ecnu.ecgbackend.config.security.filter;


import ecnu.ecgbackend.config.redis.RedisService;
import ecnu.ecgbackend.config.security.exception.CustomerAuthenticationException;
import ecnu.ecgbackend.config.security.handler.LoginFailureHandler;
import ecnu.ecgbackend.config.security.service.CustomerUserDetailsService;
import ecnu.ecgbackend.utils.JwtUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Data
@Component
public class CheckTokenFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private RedisService redisService;
    @Value("/account/login")
    private String loginUrl;
    @Value("/account/register")
    private String registerUrl;
    @Value("/common/code")
    private String registerCodeUrl;
    @Value("/common/verify")
    private String verifyUrl;
    @Value("/common/verify/code")
    private String verifyCodeUrl;
    @Value("/account/password")
    private String passwordUrl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String[] urls={loginUrl,registerUrl,registerCodeUrl,verifyUrl,verifyCodeUrl,passwordUrl};
        List<String> filterUrls= Arrays.asList(urls);
        try{
            String url=request.getRequestURI();
            if(!filterUrls.contains(url)){//如果不是登录页面就去验证token
                this.validateToken(request);
            }
        }catch (AuthenticationException e){
            loginFailureHandler.onAuthenticationFailure(request,response,e);
        }
        doFilter(request,response,filterChain);
    }
    private void validateToken(HttpServletRequest request)throws AuthenticationException{
        String token=request.getHeader("token");
        if(ObjectUtils.isEmpty(token)){
            token=request.getParameter("token");
        }
        if(ObjectUtils.isEmpty(token)){
            throw new CustomerAuthenticationException("token不存在");
        }
        String tokenKey="token_"+token;
        String redisToken=redisService.get(tokenKey);
        if(ObjectUtils.isEmpty(redisToken)){
            throw new CustomerAuthenticationException("token已过期");
        }
        if(!token.equals(redisToken)){
            throw new CustomerAuthenticationException("token验证失败");
        }
        String username=jwtUtils.getUsernameFromToken(token);
        if(ObjectUtils.isEmpty(username)){
            throw new CustomerAuthenticationException("token解析失败");
        }
        UserDetails userDetails=customerUserDetailsService.loadUserByUsername(username);
        if(userDetails==null){
            throw new CustomerAuthenticationException("token验证失败");
        }
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(
                userDetails,null,userDetails.getAuthorities()
        );
        authenticationToken.setDetails(
                new WebAuthenticationDetailsSource().buildDetails(request)
        );
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
